<?php
//tag.php
//yc@2009-10-21 14:55:18
class Tag extends Model
{
    private $db;

    public function __construct()
    {
        $this->db = loadLib('DbMysql');
    }

    public function find($id)
    {
        return $this->db->fetchRow('tag', 'id='.$id);    
    }
    public function getTagByName($tag)
    {
        $tag = clearSlashes($tag);
        return $this->db->fetchRow('tag', "tag='{$tag}'");
    }

    public function countBlogByTagIds($tagIds)
    {
        return $this->db->fetchResult('tag', 'sum(counts)', 'id IN ('.implode(',', $tagIds).')');
    }

    public function getTagsByIds($ids)
    {
        if (empty($ids))
            return;
        $sql = 'SELECT * FROM tag WHERE id IN(' . implode(',', $ids) . ')';
        $ret = array();
        foreach ($this->db->fetchAll($sql) as $tag){
            $ret[$tag['id']] = $tag;
        }
        return $ret;
    }

    public function getTopTags($count)
    {
        if (is_int($count))
            return $this->db->fetchAll('SELECT * FROM tag ORDER BY counts DESC LIMIT ' . $count);
    }

    public function getAll($order = null)
    {
        is_null($order) && ($order = 'RAND()');
        return $this->db->fetchAll('SELECT * FROM tag ORDER BY ' . $order);
    }

    public function addNewTag($tag)
    {
        $tag = clearSlashes($tag);
        $row = $this->getTagByName($tag);
        if ($row){
            $this->updateCountById($row['id']);
            return $row['id'];
        }
        $this->db->insert('tag', array('tag' => $tag));
        return $this->db->lastInsertId();
    }

    public function updateCountById($id)
    {
        //return $this->db->update('tag', );
        return $this->db->query('UPDATE tag SET counts=counts+1 WHERE id=' . $id);
    }

    public function decreaseCount($id)
    {
        $tag = $this->find($id);
        if ($tag){
            if ($tag['counts'] <= 1)//delete it
                $this->delete($id);
            else
                $this->db->query('UPDATE tag SET counts=counts-1 WHERE id=' . $id);
        }
    }

    public function delete($id)
    {
        return $this->db->query('DELETE FROM tag WHERE id=' . $id);
    }
}
?>
